import { AttachmentObject, CaseDataItem, DResponse, ValueObject } from '@/pages/routes/table/interface';
import { EnumObject } from '@/pages/routes/table/QueryForm';
import Http from '@/utils/http';
import moment from 'moment';

interface QueryCaseOptions {
  name: string;
  type: number;
  area: number;
  createUser: number;
  /**
   * 本点号
   */
  bdh: string;
  updateDate: [string, string];
  startDate: [string, string];
  endDate: [string, string];
  format?: 'json';
  page: number;
  pageSize: number;
}

/**
 * 获取方案列表
 * @param options
 */
export async function queryCaseList(
  options: QueryCaseOptions
): Promise<DResponse<{ total: number; list: CaseDataItem[] }>> {
  // /plan/queryBaseInfo
  // {PLAN_NAME: name}
  const {
    name,
    type,
    format = 'json',
    area,
    createUser,
    bdh,
    updateDate,
    startDate,
    endDate,
    page,
    pageSize,
  } = options;
  const params: Record<string, any> = { f: format, pageno: page, pagesize: pageSize };
  if (name !== '') {
    params.PLAN_NAME = name;
  }
  if (type !== -1) {
    params.PLAN_TYPE = type;
  }
  if (area !== -1) {
    params.PLAN_AREA = area;
  }
  if (createUser !== -1) {
    params.CREATE_USER_NAME = createUser;
  }
  if (bdh !== '') {
    params.GUID = bdh;
  }
  if (updateDate[0] && updateDate[1]) {
    params.MOD_TIME = updateDate.join(',');
  }
  if (startDate[0] && startDate[1]) {
    params.PLAN_START_TIME = startDate.join(',');
  }
  if (endDate[0] && endDate[1]) {
    params.PLAN_END_TIME = endDate.join(',');
  }
  return Http.get({
    url: 'http://localhost:9014/proxyZhuzhou/zhuzhou/ecity/zzgs/plan/queryBaseInfo',
    data: {
      ...params,
    },
  }).then((res) => {
    return {
      code: res.success ? 0 : -1,
      msg: '获取成功',
      data: {
        total: res.count,
        list: res.results.map((i: any) => ({
          id: i.GID,
          name: i.PLAN_NAME,
          type: i.PLAN_TYPE,
          area: i.PLAN_AREA,
          createUser: i.CREATE_USER_NAME,
          updateDate: i.MOD_TIME,
          startDate: i.PLAN_START_TIME.substr(0, i.PLAN_START_TIME.indexOf(' ')),
          endDate: i.PLAN_END_TIME.substr(0, i.PLAN_START_TIME.indexOf(' ')),
          remark: i.REMARK,
        })),
      },
    };
  });

  // const res = {
  //   success: true,
  //   count: 20,
  //   results: [
  //     {
  //       GID: '1',
  //       GUID: '3724a7ee-a7b7-4e7a-b385-962acc8a6a20',
  //       PLAN_NAME: '调度方案1',
  //       PLAN_TYPE: 1,
  //       PLAN_AREA: 2,
  //       CREATE_USER_NAME: '张三',
  //       MOD_TIME: '2021-11-06 11:00:00',
  //       PLAN_START_TIME: '2021-11-06 11:00:00',
  //       PLAN_END_TIME: '2021-11-08 11:00:00',
  //       REMARK: '备注',
  //       PLAN_PATH: '/map/output/xxxx.pdf',
  //     },
  //     {
  //       GID: '2',
  //       GUID: '3724a7ee-a7b7-4e7a-b385-962acc8a6a21',
  //       PLAN_NAME: '调度方案2',
  //       PLAN_TYPE: 1,
  //       PLAN_AREA: 2,
  //       CREATE_USER_NAME: '张三',
  //       MOD_TIME: '2021-11-06 11:00:00',
  //       PLAN_START_TIME: '2021-11-06 11:00:00',
  //       PLAN_END_TIME: '2021-11-08 11:00:00',
  //       REMARK: '备注',
  //       PLAN_PATH: '/map/output/xxxx.pdf',
  //     },
  //     {
  //       GID: '2',
  //       GUID: '3724a7ee-a7b7-4e7a-b385-962acc8a6a22',
  //       PLAN_NAME: '调度方案3',
  //       PLAN_TYPE: 1,
  //       PLAN_AREA: 2,
  //       CREATE_USER_NAME: '王五',
  //       MOD_TIME: '2021-11-06 11:00:00',
  //       PLAN_START_TIME: '2021-11-06 11:00:00',
  //       PLAN_END_TIME: '2021-11-08 11:00:00',
  //       REMARK: '备注',
  //       PLAN_PATH: '/map/output/xxxx.pdf',
  //     },
  //   ],
  // };
  // return {
  //   code: res.success ? 0 : -1,
  //   msg: '获取成功',
  //   data: {
  //     total: res.count,
  //     list: res.results.map((i) => ({
  //       id: i.GID,
  //       name: i.PLAN_NAME,
  //       type: i.PLAN_TYPE,
  //       area: i.PLAN_AREA,
  //       createUser: i.CREATE_USER_NAME,
  //       updateDate: i.MOD_TIME,
  //       startDate: i.PLAN_START_TIME.substr(0, i.PLAN_START_TIME.indexOf(' ')),
  //       endDate: i.PLAN_END_TIME.substr(0, i.PLAN_START_TIME.indexOf(' ')),
  //       remark: i.REMARK,
  //     })),
  //   },
  // };
}

/**
 * 获取区域列表
 */
export async function getAreaList(): Promise<DResponse<EnumObject[]>> {
  const areaList = [
    {
      value: 1,
      title: '荷塘区',
    },
    {
      value: 2,
      title: '芦淞区',
    },
    {
      value: 3,
      title: '天元区',
    },
    {
      value: 4,
      title: '石峰区',
    },
    {
      value: 5,
      title: '云龙区',
    },
  ];
  return {
    code: 0,
    data: areaList,
    msg: '获取成功',
  };
}

export async function getTypeList(): Promise<DResponse<EnumObject[]>> {
  const typeList = [
    {
      value: 1,
      title: '明漏抢修',
    },
    {
      value: 2,
      title: '暗漏抢修',
    },
    {
      value: 3,
      title: '施工挖坏',
    },
    {
      value: 4,
      title: '管线碰头',
    },
    {
      value: 5,
      title: '改管',
    },
    {
      value: 6,
      title: '管线冲洗',
    },
  ];
  return {
    code: 0,
    data: typeList,
    msg: '获取成功',
  };
}

export async function getCreateUser(): Promise<DResponse<EnumObject[]>> {
  const createUerList = [
    {
      value: 1,
      title: '张三',
    },
    {
      value: 2,
      title: '李四',
    },
    {
      value: 3,
      title: '王五',
    },
    {
      value: 4,
      title: '二麻子',
    },
  ];
  return {
    code: 0,
    data: createUerList,
    msg: '获取成功',
  };
}

export async function createCase(options: ValueObject): Promise<DResponse<{ id: string }>> {
  const { name, type, area, startDate, endDate, ts, hf, ds, scdd, gwyx, bmzz, scyx, mark } = options;
  return Http.post<{ success: boolean; gid: string }>({
    // svr: '',
    // path: '/plan/add',
    url: 'http://localhost:9014/proxyZhuzhou/zhuzhou/ecity/zzgs/plan/add',
    type: Http.BodyType.FORM,
    data: `planData=${JSON.stringify({
      planInfo: {
        PLAN_NAME: name,
        PLAN_TYPE: type,
        PLAN_AREA: area,
        CREATE_USER_NAME: '张三',
        PLAN_START_TIME: startDate!.format('YYYY-MM-DD HH:mm:ss'),
        PLAN_END_TIME: endDate!.format('YYYY-MM-DD HH:mm:ss'),
        WATER_DISPATCH: scdd,
        WATER_EFFECT: scyx,
        NET_EFFECT: gwyx,
        REMARK: mark,
      },
      equInfos: [
        ts.map((v) => ({
          LAYERNAME: v.ownNet,
          EQU_ID: v.dbh,
          LOCATION: v.description,
          OPER_STATE: v.checked ? 'open' : 'close',
          DISPATCH_TYPE: 0,
        })),
        ds.map((v) => ({
          LAYERNAME: v.ownNet,
          EQU_ID: v.dbh,
          LOCATION: v.description,
          OPER_STATE: v.checked ? 'open' : 'close',
          DISPATCH_TYPE: 1,
        })),
        hf.map((v) => ({
          LAYERNAME: v.ownNet,
          EQU_ID: v.dbh,
          LOCATION: v.description,
          OPER_STATE: v.checked ? 'open' : 'close',
          DISPATCH_TYPE: 2,
        })),
      ],
      departmentInfos: bmzz.map((v) => ({
        DEPARTMENT_NAME: v.department,
        DEPARTMENT_DUTY: v.description,
      })),
    })}`,
  }).then((res) => {
    if (!res.success) {
      return {
        code: -1,
        data: {
          id: '-1',
        },
        msg: '创建失败',
      };
    }
    return {
      code: 0,
      data: {
        id: '1002',
      },
      msg: '创建成功',
    };
  });
}

export async function updateCase(options: ValueObject): Promise<DResponse> {
  const { name, type, area, startDate, endDate, ts, hf, scdd, gwyx, bmzz, mark } = options;
  return Http.post<{ success: boolean; gid: string }>({
    svr: '',
    path: '/plan/update',
    url: 'http://localhost:9014/proxyZhuzhou/zhuzhou/ecity/zzgs/plan/add',
    data: {
      planData: JSON.stringify({
        planInfo: {
          PLAN_NAME: name,
          PLAN_TYPE: type,
          PLAN_AREA: area,
          CREATE_USER_NAME: '张三x',
          PLAN_START_TIME: startDate!.format('YYYY-MM-DD HH:mm:ss'),
          PLAN_END_TIME: endDate!.format('YYYY-MM-DD HH:mm:ss'),
          WATER_DISPATCH: ts,
          WATER_EFFECT: scdd,
          NET_EFFECT: gwyx,
          REMARK: mark,
        },
      }),
    },
  }).then((res) => {
    if (!res.success) {
      return {
        code: -1,
        data: {
          id: '-1',
        },
        msg: '创建失败',
      };
    }
    return {
      code: 0,
      data: {
        id: '1002',
      },
      msg: '创建成功',
    };
  });
}

export async function queryCreateUsers() {}

interface QueryDetailOptions {
  f?: string;
  id: string;
}

export async function getCaseDetail(options: QueryDetailOptions) {
  return Http.get<{ success: boolean; result: any }>({
    url: 'http://localhost:9014/proxyZhuzhou/zhuzhou/ecity/zzgs/plan/queryDetailInfo',
    data: {
      f: 'json',
      PLANT_ID: options.id,
    },
  }).then((ss: any) => {
    const { PLAN_NAME, PLAN_TYPE, GID, PLAN_AREA, NET_EFFECT, REMARK, PLAN_END_TIME, PLAN_START_TIME } =
      ss.result.planInfo;
    const equInfos = ss.result.equInfos;
    const ds = equInfos
      .filter((v: any) => v.DISPATCH_TYPE === 0)
      .map((v: any) => ({
        id: String(v.GID),
        ownNet: v.LAYERNAME,
        dbh: v.EQU_ID,
        description: v.LOCATION,
        checked: v.OPER_STATE === 'open',
      }));
    const ts = equInfos
      .filter((v: any) => v.DISPATCH_TYPE === 1)
      .map((v: any) => ({
        id: String(v.GID),
        ownNet: v.LAYERNAME,
        dbh: v.EQU_ID,
        description: v.LOCATION,
        checked: v.OPER_STATE === 'open',
      }));
    const hf = equInfos
      .filter((v: any) => v.DISPATCH_TYPE === 2)
      .map((v: any) => ({
        id: String(v.GID),
        ownNet: v.LAYERNAME,
        dbh: v.EQU_ID,
        description: v.LOCATION,
        checked: v.OPER_STATE === 'open',
      }));
    const bmzz = ss.result.departmentInfos.map((v: any) => ({
      id: String(v.GID),
      department: v.DEPARTMENT_NAME,
      description: v.DEPARTMENT_DUTY,
    }));
    return {
      code: 0,
      data: {
        // id:GID,
        name: PLAN_NAME,
        type: PLAN_TYPE,
        area: PLAN_AREA,
        startDate: moment(PLAN_START_TIME),
        endDate: moment(PLAN_END_TIME),
        ds,
        ts,
        hf,
        scdd: '',
        gwyx: NET_EFFECT,
        bmzz,
        mark: REMARK,
      },
      msg: '',
    };
  });
}

interface QueryAttachmentOptions {
  layerId: number;
  objectId: number;
}

/**
 * 查询附件列表
 * @param params
 * @returns {Promise<{msgCode: number, message: string, data: null}>}
 */
export async function getAttachmentList(params: QueryAttachmentOptions) {
  const { objectId } = params;
  return Http.get<{ attachmentInfos: AttachmentObject[] }>({
    url: `http://localhost:8996/proxyHopeServer/hopeserver/rest/services/NetServer/cstrq/table/GISERRORREPORT_BASE/${objectId}/attachments`,
    // path: `${layerId}/${objectId}/attachments`,
    data: {
      where: '1=1 AND order by adddate desc',
    },
  }).then((res) => ({
    msg: '获取成功',
    code: 0,
    data: res.attachmentInfos.map((item) => ({
      url: item.virurl,
      time: item.adddate,
      name: item.name,
      size: item.size,
      type: item.type,
      contentType: item.contentType,
      origin: { ...item },
    })),
  }));
}

interface UploadAttachmentOptions {
  objectId: string;
  attachment: File;
  filename?: string;
  f?: string;
  remark?: string;
  dbtype?: number;
  dir?: string;
  type?: string;
}

interface UploadAttachmentResponse {
  addAttachmentResult: {
    objectId: string;
    success: boolean;
  }[];
}

/**
 * 上传附件
 * @param options
 */
export function uploadAttachment(options: UploadAttachmentOptions) {
  // http://localhost:8996/proxyHopeServer/hopeserver/rest/services/NetServer/cstrq/table/GISERRORREPORT_BASE/11/addAttachment?access_token=eea789827e525309546aa56328fd3ce8
  const { objectId, ...resetProps } = options;
  return Http.post<UploadAttachmentResponse>({
    url: `http://localhost:8996/proxyHopeServer/hopeserver/rest/services/NetServer/cstrq/table/GISERRORREPORT_BASE/${objectId}/addAttachment`,
    url: `http://localhost:7027/proxyHopeServer/hopeserver/rest/services/NetServer/cstrq/table/GISERRORREPORT_BASE/${objectId}/addAttachment`,
    path: `table/GISERRORREPORT_BASE/${objectId}/addAttachment`,
    data: {
      ...resetProps,
    },
    type: Http.BodyType.FORM_DATA,
  }).then((res) => ({
    msg: '',
    data: res.addAttachmentResult,
    code: 0,
  }));
}
